package com.example.springbootaop.aspect;

import com.example.springbootaop.annotation.EntityLog;
import com.example.springbootaop.pojo.MyEntity;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Arrays;

/**
 * @author wangzhenjun
 * @date 2022/10/26 15:39
 */

@Aspect
@Component
public class EntityAspect {

    /**
     * 以注解所标注的方法作为切入点
     */
    @Pointcut("execution(* com.example.springbootaop.controller..*.*(..))")
    public void entityLog() {
    }

    @Before("entityLog()")
    public void doSomething(JoinPoint joinPoint) throws NoSuchMethodException {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Class<?> clazz = joinPoint.getTarget().getClass();
        Method method = clazz.getMethod(signature.getName(), signature.getParameterTypes());

        //获取实体类上的注解信息
        Object[] args = joinPoint.getArgs();
        MyEntity myEntity = (MyEntity)args[0];
        EntityLog entityAnnotation = myEntity.getClass().getAnnotation(EntityLog.class);
        if("MyEntity".equals(entityAnnotation.value())){
            System.out.printf("[Entity前置通知]: [目标类]:%s , [方法]:%s , [入参值]:%s%n"
                    , clazz.getName(), method.getName(), Arrays.toString(joinPoint.getArgs()));
        }

    }
}


